﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;

namespace CPPEI.PM.Service.Model.Repository
{
    public class WorkItemCategoryRepository
    {
        private DbContext _dbContext;
        public WorkItemCategoryRepository(DbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public void Create(WorkItemCategory workItemCategory)
        {
            _dbContext.Set<WorkItemCategory>().Add(workItemCategory);
        }

        public WorkItemCategory Get(Guid id)
        {
            return _dbContext.Set<WorkItemCategory>().SingleOrDefault(p => p.Id == id);
        }

        public WorkItemCategory GetByCode(Guid projectId, string code)
        {
            return _dbContext.Set<WorkItemCategory>().Single(p => p.ProjectId == projectId && p.Code == code);
        }

        public WorkItemCategory GetBySheet(Guid workSheetId)
        {
            return _dbContext.Set<WorkItemCategory>().Join(_dbContext.Set<WorkItemCategoryRef>().Where(p => p.WorkSheetId == workSheetId && p.ParentWorkItemcategoryId == Guid.Empty),
                l => l.Id,
                r => r.WorkItemCategoryId,
                (l, r) => l).SingleOrDefault();
        }

        public List<WorkItemCategory> GetBySheet(Guid workSheetId, Guid parentWorkItemCategoryId)
        {
            return _dbContext.Set<WorkItemCategory>().Join(_dbContext.Set<WorkItemCategoryRef>().Where(p => p.WorkSheetId == workSheetId && p.ParentWorkItemcategoryId == parentWorkItemCategoryId),
                l => l.Id,
                r => r.WorkItemCategoryId,
                (l, r) => l).ToList();
        }
    }
}
